from starlette.authentication import (
    AuthenticationBackend, AuthenticationError, SimpleUser,
    AuthCredentials
)


class UsernameAuthBackend(AuthenticationBackend):
    def __init__(self, username):
        self.username = username

    async def authenticate(self, request):
        if "Authorization" not in request.headers:
            return

        auth = request.headers["Authorization"]

        try:
            scheme, username = auth.split()
            if scheme.lower().strip() != 'bearer'.strip():
                return
        except Exception:
            raise AuthenticationError('Invalid basic auth credentials')
        if not username == self.username:
            return

        return AuthCredentials(["authenticated"]), SimpleUser(username)
